import http from 'http';
import fs from 'fs';
const port = 9000
const folder = 'public'

import crypto  from 'crypto';
import ws from "ws";
// const Client = require("@gradio/client");
import { client } from "@gradio/client";


async function asr(){
    const app = await client("http://localhost:9874/");
    const result = await app.predict("/only_asr", [		
        "达摩 ASR (中文)", // string  in 'ASR 模型' Dropdown component
]);
    console.log(result)
    
}
asr();
function initWebSocket(){
    const host = 'spark-api.xf-yun.com';
    const path = '/v1.1/chat';
    const APISecret = 'NjZmNWE2Nzg1YTcwYWI2Njc5YWY5ZjY5';
    const APIKey = '86a7c023f4d129e86efd12f97a8527b5';
    const dateString = new Date().toGMTString();
    let tmp = "host: " + host + "\n"
    tmp += "date: " + dateString + "\n"
    tmp += "GET " + path + " HTTP/1.1"
    let signature = crypto.createHmac('sha256', APISecret).update(tmp).digest('base64');
    const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`;
    let buff = Buffer.from(authorization_origin);
    const authorization = buff.toString('base64');

    const signUrl = `wss://${host}${path}?authorization=${authorization}&date=${encodeURIComponent(dateString).replace(/%20/g,"+")}&host=${host}`
    let sock = new ws(signUrl);
    sock.on("open", function() {
        console.log("connect success !!!!");

        sock.send(JSON.stringify({
			"header": {
				"app_id": '1e13253e',//替换成自己的app_id
				// "uid": "fd3f47e4-d",//最大长度32	每个用户的id，用于区分不同用户
			},
			"parameter": {
				"chat": {
					"domain": "lite",
					"temperature": 0.5,
					"max_tokens": 1024, //模型回答的tokens的最大长度
				}
			},
			"payload": {
				"message": {
					"text": [{
						"role": "user",
						"content": "1加1等于几"
					}, ]
				}
			}
		}))
    });
    sock.on("error", function(err) {
        console.log("error: ", err);
    });
    sock.on("close", function() {
        console.log("close");
    });
    sock.on("message", function(data) {
        console.log("message", data.toString());
    });
}
// initWebSocket();
http.createServer(function (req, res) {
    var pathname = req.url;
    if (pathname == '/') {
        pathname = '/index.html'; /*默认加载的首页*/
    }
    fs.readFile(folder + pathname, async (err, data) => {
        res.writeHead(200, { "Content-Type": "text/html;charset='utf-8'" });
        res.write(data);
        res.end();
    })
}).listen(port);
console.log(`Server running at http://127.0.0.1:${port} `);